import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

const baseURL = 'http://127.0.0.1:8081'

export async function request(url, options = {}) {
    const authStore = useAuthStore();
    const headers = {
      'Content-Type': 'application/json',
      ...options.headers
    };
    
    const token = localStorage.getItem('access-token');
    if (token) {
      headers['access-token'] = token;
    }
    
    try {
      const response = await fetch(`${baseURL}${url}`, {
        ...options,
        headers
      });
      
      if (!response.ok) {
        const error = await response.json();
        if (response.status === 401) {
          // token 过期或无效，自动退出登录
          await authStore.logout();
          ElMessage.error('登录已过期，请重新登录');
          window.location.reload();
        }
        throw new Error(error.message || '请求失败');
      }
      
      return await response.json();
    } catch (error) {
      throw error;
    }
  }